

#import "PWBannerView.h"
//#import "UIImageView+WebCache.h"

static NSString * const cellIdentifier = @"PWBannerView";
static NSInteger const PWMaxSection = 8888;

@interface PWBannerView ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@end

@implementation PWBannerView

- (void)dealloc{
    [self removeTimer];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.flowLayout.itemSize = self.bounds.size;
    self.collectionView.frame = self.bounds;
}

- (void)reloadData{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:PWMaxSection / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    [self.collectionView reloadData];
    [self removeTimer];
    [self addTimer];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return PWMaxSection;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(_imageNames.count){
        return _imageNames.count;
    }
    else if (_imageURLs.count){
        return _imageURLs.count;
    }
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    UIImageView *imageView = [cell viewWithTag:0x0FF];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    if(imageView == nil){
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.tag = 0x0FF;
        [cell.contentView addSubview:imageView];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    UIImageView *imageView = [cell viewWithTag:0x0FF];
    imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    if(_imageNames.count){
        imageView.image = [UIImage imageNamed:_imageNames[indexPath.item]];
    }
    else if (_imageURLs.count){
        NSURL *imageURL = [NSURL URLWithString:[_imageURLs[indexPath.item] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [imageView sd_setImageWithURL:imageURL placeholderImage:_placeholderImage];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if([self.delegate respondsToSelector:@selector(bannerView:didSelectAtIndex:)]){
        [self.delegate bannerView:self didSelectAtIndex:indexPath.item];
    }
}

- (void)nextPage{
    if(_imageURLs.count || _imageNames.count){
        NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
        NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:PWMaxSection / 2];
        [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        
        NSInteger nextItem = currentIndexPathReset.item + 1;
        NSInteger nextSection = currentIndexPathReset.section;
        if (nextItem == _imageURLs.count || nextItem ==_imageNames.count) {
            nextItem = 0;
            nextSection++;
        }
        currentIndexPathReset = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
        [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }
}

- (void)addTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:_timerInterval target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)removeTimer{
    [_timer invalidate];
    _timer = nil;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if(_autoScroll){
        [self addTimer];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger count = self.imageNames.count?:self.imageURLs.count;
    if (count==0) return;
    if([self.delegate respondsToSelector:@selector(bannerView:nextPageAtIndex:)]){
        [self.delegate bannerView:self nextPageAtIndex:(NSInteger)(scrollView.contentOffset.x / scrollView.bounds.size.width + 0.5) % count];
    }
}

- (void)initialization{
    _timerInterval = 5;
    _autoScroll = YES;
    [self addTimer];
    [self addSubview:self.collectionView];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:PWMaxSection / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

- (instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        [self initialization];
    }
    return self;
}

- (instancetype)init{
    if(self = [super init]){
        [self initialization];
    }
    return self;
}

- (void)setImageNames:(NSArray<NSString *> *)imageNames{
    _imageNames = imageNames;
    [self reloadData];
}

- (void)setImageURLs:(NSArray<NSString *> *)imageURLs{
    _imageURLs = imageURLs;
    [self reloadData];
}

- (void)setAutoScroll:(BOOL)autoScroll{
    _autoScroll = autoScroll;
    if(autoScroll){
        [self removeTimer];
        [self addTimer];
    }
    else{
        [self removeTimer];
    }
}

- (void)setTimerInterval:(NSTimeInterval)timerInterval{
    _timerInterval = timerInterval;
    if(_autoScroll){
        [self removeTimer];
        [self addTimer];
    }
}

- (UICollectionView *)collectionView{
    if(_collectionView == nil){
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = self.frame.size;
        self.flowLayout = flowLayout;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = randomColor;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
//        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    }
    return _collectionView;
}

@end
